<template>
  <div id="app">
    <h2>小李日志</h2>
    <myHeader @addItem="addItem" />
    <list :todos="todos"/>
    <myFooter :checkNum="checkNum" :totalNum="totalNum" 
    @FooterCheck='FooterCheck' @clearItems='clearItems'/>
  </div>
</template>

<script>
import myHeader from './components/myHeader.vue'
import list from './components/List.vue'
import myFooter from './components/myFooter.vue'
export default {
  name: 'App',
  components:{myHeader, myFooter, list},
  data() {
    return {
      todos: [
        {id:"001", name:"打代码", isChanged:false},
        {id:'002', name:"睡觉", isChanged:true},
        {id:'003', name:"吃饭", isChanged:false},
      ]
    }
  },
  methods: {
    // 添加一个todo
    addItem(obj) {
      this.todos.unshift(obj)
    },
    // 勾选or取消勾选todo
    checkTodo(id) {
      let target = this.todos.find( element => element.id === id )
      target.isChanged = !target.isChanged
    },
    // 删除一个todo
    deleteTodo(id) {
      this.todos = this.todos.filter(item => {
        return item.id !== id
      })
    },
    FooterCheck(flag) {
      let val = flag == 1 ? true : false
      this.todos.forEach(item=>item.isChanged = val)
    },
    // 删除已完成任务
    clearItems() {
      this.todos = this.todos.filter(item => {
        return !item.isChanged
      })
    }
  },
  mounted() {
    this.$bus.$on('checkTodo',this.checkTodo)
    this.$bus.$on('deleteTodo',this.deleteTodo)
  },
  beforeDestroy() {
    this.$bus.$off(['checkTodo','deleteTodo'])
  },
  computed: {
    checkNum() {
      let result = 0
      this.todos.forEach(item => {
          if(item.isChanged) result++;
      });
      return result
    },
    totalNum() {
      return this.todos.length
    },
  }
}
</script>

<style>
#app{
  width: 500px;
  margin: 10px auto;
  border: 1px solid #e2e2e2;
  padding: 10px;
}
*{
  padding: 0;
  margin: 0;
}
.btn {
  padding: 3px 9px;
  border: 2px solid #f00;
  border-radius: 4px;
}
.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #db362f;
}
.btn-edit {
   color: #fff;
  background-color: skyblue;
  border: 1px solid rgb(59, 117, 139);
  margin-right: 10px;
}
.btn-danger:hover {
  color: #fff;
  background-color: #db362f;
}
.btn:focus {
  outline: none;
}

</style>
